package com.qf.j2112.controller.alipay;


import com.alipay.api.AlipayApiException;
import com.qf.j2112.alipay.AliReturnPayBean;
import com.qf.j2112.alipay.AlipayOrder;
import com.qf.j2112.service.AliPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: jeffrey
 * @Date: 2022/03/13/21:47
 * @Description: 支付宝沙箱测试 controller
 */
@RestController
@Slf4j
@CrossOrigin
public class PayController {

    @Autowired
    private AliPayService aliPayService;

    /**
     * 支付宝支付 api
     * @param outTradeNo
     * @param subject
     * @param totalAmount
     * @param description
     * @return
     * @throws AlipayApiException
     */
    @PostMapping(value = "/alipay")
    public String alipay(String outTradeNo,
                         String subject,
                         String totalAmount,
                         String description) throws AlipayApiException {
        AlipayOrder order = new AlipayOrder();
        order.setOut_trade_no(outTradeNo);
        System.out.println(outTradeNo);
        order.setSubject(subject);
        order.setTotal_amount(totalAmount);
        order.setDescription(description);
        System.out.println(order);

//       2.1 写入订单，并将订单状态置为：未支付

        return aliPayService.aliPay(order);
    }

    /**
     * 支付宝支付成功后，还未同步显示成功页面前异步调用的业务接口
     * @param request  （含有支付成功的签名）
     * @param response
     * @param returnPay
     * @throws IOException
     */
    @RequestMapping("/call")
    public void notify(HttpServletRequest request, HttpServletResponse response, AliReturnPayBean returnPay) throws IOException {
        log.info("支付宝的回调函数被调用");
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("return pay:"+returnPay);
        if(!aliPayService.checkSign(request)){  //再次调用阿里的接口进行验签
           log.info("===验签失败===");
           response.getWriter().write("failtrue");
           return ;
        }
        if(returnPay==null){
            log.info("支付宝returnPay返回为空");
            response.getWriter().write("success");
            return ;
        }
        if (returnPay.getTrade_status().equals("TRADE_SUCCESS")){
            log.info("======支付成功====");
//           4.1 修改订单状态为：已支付
            response.getWriter().write("success");
        }

    }
}
